package cn.gnp.framework.web;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.imageio.ImageIO;

public class CaptchaImageServlet extends HttpServlet {
	private ApplicationContext context;

	private static final long serialVersionUID = 5274323889605521606L;

	@Override
	public void init() throws ServletException {
		super.init();
		context = WebApplicationContextUtils
				.getWebApplicationContext(getServletContext());
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String key = request.getParameter("key");

		if (key == null || key.length() == 0) {
			response.sendError(400, "No Captcha Key Found");
		} else {
			response.setContentType("image/jpeg");
			OutputStream out = response.getOutputStream();
			out.write(generateCaptchaImage(key));
			out.close();
		}
	}

	public byte[] generateCaptchaImage(String captchaKey) {

		DefaultKaptcha producer = new DefaultKaptcha();

        producer.setConfig( new Config( new Properties() ) );		
		BufferedImage image = producer.createImage(captchaKey);

		ByteArrayOutputStream out = new ByteArrayOutputStream();

		try {
			ImageIO.write(image, "jpg", out);
		} catch (IOException e) {
		}

		return out.toByteArray();
	}
}
